<?php

namespace App\Org\code;

class Code{
    function code() {
        $codes = "";
        $width = 100;
        $height = 50;
        // 生成验证码的画布
        $image = imagecreatetruecolor($width, $height);
        $gray = imagecolorallocate($image, 200, 200, 200);
        $red = mt_rand(1, 199);
        $green = mt_rand(1, 199);
        $blue = mt_rand(1, 199);
        // 使用rgb来获取产生字体的字体颜色
        $color = imagecolorallocate($image, $red, $green, $blue);
        imagefill($image, 0, 0, $gray);
        // 0-9 a-z 的随机数
        $string = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
        for ($i = 0; $i < 4; $i++) {
            $size = mt_rand(20, 30);
            $angle = mt_rand(-15, 15);
            $x = 100 / 4 * $i;
            $by = (50 - $size) / 2 + $size;
            $y = mt_rand($by * 0.8, $by * 1.2);
//            $fontfile = __DIR__ . '/GiddyupStd.otf';  //可自己更换字体
            $fontfile = __DIR__ . '/STXINWEI.TTF';  //可自己更换字体
            $info = mt_rand(0, strlen($string) - 1);
            $text = $string[$info];
            imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text);
            $codes .= $text;
        }
        session(['code' => $codes]);
        // 为了防止机器人操作添加干扰
        for ($i = 0; $i < 10; $i++) {
            $x1 = mt_rand(0, 100);
            $y1 = mt_rand(0, 50);
            $x2 = mt_rand(0, 100);
            $y2 = mt_rand(0, 50);
            imageline($image, $x1, $y1, $x2, $y2, $color);
        }
        // 转化图片的生成的形式
        header('content-type:image/png');
        imagepng($image);
        imagedestroy($image);
    }

}